import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { useState, useEffect } from 'react';
import axios from 'axios';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import Login from './pages/Login';
import Register from './pages/Register';
import Documents from './pages/Documents';
import Editor from './pages/Editor';
import Profile from './pages/Profile';
import SharedDoc from './pages/SharedDoc';
import Shared from './pages/Shared';
import ForgotPassword from './pages/ForgotPassword';
import AISettings from './pages/AISettings';
import config from './config';
import './pages/styles.css';
import './App.css';

// 设置axios默认配置
axios.defaults.baseURL = config.api.baseUrl;
axios.defaults.withCredentials = true; // 启用凭证
axios.defaults.timeout = 10000; // 增加超时设置，10秒
console.log('API基础URL:', axios.defaults.baseURL);

// 添加请求拦截器
axios.interceptors.request.use(requestConfig => {
  const method = requestConfig.method?.toUpperCase() || 'GET';
  const url = requestConfig.url;
  console.log(`[请求] ${method} ${url}`, requestConfig.data ? `数据: ${JSON.stringify(requestConfig.data).substring(0, 100)}...` : '');
  
  // 从localStorage获取token并添加到请求头
  const token = localStorage.getItem(config.auth.TOKEN_KEY);
  if (token) {
    requestConfig.headers.Authorization = `Bearer ${token}`;
    console.log('已添加认证令牌');
  }
  
  return requestConfig;
}, error => {
  console.error('[请求错误]', error.message || error);
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {
  const { status, config } = response;
  const method = config.method?.toUpperCase() || 'GET';
  const url = config.url;
  
  console.log(`[响应] ${method} ${url} - 状态: ${status}`, 
    response.data ? `数据: ${JSON.stringify(response.data).substring(0, 100)}...` : '');
  
  return response;
}, error => {
  if (error.response) {
    // 服务器响应了错误状态码
    const { status, data, config } = error.response;
    const method = config.method?.toUpperCase() || 'GET';
    const url = config.url;
    
    console.error(`[响应错误] ${method} ${url} - 状态: ${status}`, 
      data ? `错误: ${JSON.stringify(data)}` : '');
    
    // 处理401未授权错误 - Token失效自动跳转
    if (status === 401) {
      console.warn('认证失败，Token已失效，准备跳转到登录页面');
      
      // 清除本地存储的认证信息
      localStorage.removeItem(config.auth.TOKEN_KEY);
      localStorage.removeItem(config.auth.USER_INFO_KEY);
      
      // 检查当前是否不在登录页面，避免无限跳转
      const currentPath = window.location.pathname;
      const isLoginPage = currentPath === '/login' || currentPath === '/register' || currentPath === '/forgot-password';
      
      if (!isLoginPage) {
        console.log('当前页面:', currentPath, '，准备跳转到登录页面');
        
        // 使用setTimeout确保在下一个事件循环中执行跳转
        setTimeout(() => {
          window.location.href = '/login';
        }, 100);
      } else {
        console.log('当前已在登录相关页面，无需跳转');
      }
    }
  } else if (error.request) {
    // 请求已发出但没有收到响应
    console.error('[网络错误] 未收到响应:', error.request);
  } else {
    // 请求设置时出错
    console.error('[请求配置错误]', error.message || error);
  }
  
  return Promise.reject(error);
});

function App() {
  const [loading, setLoading] = useState(true);
  const [serverStatus, setServerStatus] = useState('checking');
  
  useEffect(() => {
    // 检查服务器连接
    const checkServerConnection = async () => {
      try {
        await axios.get('/api/health');
        console.log('服务器连接成功');
        setServerStatus('connected');
      } catch (error) {
        console.error('服务器连接失败:', error);
        setServerStatus('disconnected');
      } finally {
        setLoading(false);
      }
    };
    
    checkServerConnection();
  }, []);
  
  if (loading) {
    return <div className="loading-screen">正在连接服务器...</div>;
  }
  
  if (serverStatus === 'disconnected') {
    return (
      <div className="error-screen">
        <h2>无法连接到服务器</h2>
        <p>请检查您的网络连接，或者联系管理员。</p>
        <button onClick={() => window.location.reload()}>重试</button>
      </div>
    );
  }
  
  // 回退到简单的认证方式，避免页面空白问题
  const isAuthenticated = localStorage.getItem(config.auth.TOKEN_KEY) !== null;

  return (
    <div className="app-container">
      <ToastContainer position="top-right" autoClose={3000} hideProgressBar={false} />
      <Router>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />
          <Route path="/forgot-password" element={<ForgotPassword />} />
          <Route path="/docs" element={
            isAuthenticated ? <Documents /> : <Navigate to="/login" />
          } />
          <Route path="/editor/:docId" element={
            isAuthenticated ? <Editor /> : <Navigate to="/login" />
          } />
          <Route path="/profile" element={
            isAuthenticated ? <Profile /> : <Navigate to="/login" />
          } />
          <Route path="/shared" element={
            isAuthenticated ? <Shared /> : <Navigate to="/login" />
          } />
          <Route path="/shared-doc/:docId" element={<SharedDoc />} />
          <Route path="/ai-settings" element={
            isAuthenticated ? <AISettings /> : <Navigate to="/login" />
          } />
          <Route path="/" element={
            isAuthenticated ? <Navigate to="/docs" /> : <Navigate to="/login" />
          } />
        </Routes>
      </Router>
    </div>
  );
}

export default App;
